<?php
namespace app\techn_api_n\controller\v1;
use app\common\logic\TechnLevelLogic;
use think\Db;
use app\service\TechnService;
use app\service\TravelService;
use app\service\TechnLastService;
class User extends Base
{
	public function _initialize()
	{
		parent::_initialize();
		$this->IsLogin(); //验证登录
		$this->IsTechn(); //验证技师
	}

	/**
	 * 用户信息
	 */
	 
	public function index()
	{
		$user = $this->user;
//		dump($user);die;
		if (!empty($user)) {
			//处理注册日期
			$user['add_time_time'] = !empty($user['add_time']) ? date('Y-m-d', $user['add_time']) : '';
		}
		
		
		
		team_get($user['id']);
		team_get2($user['upid']);
		
		
		$techn = $this->techn;

		//技师升级
		TechnLastService::TechnLevelUpgradeHandle($techn['id']);

		$techn['work_img'] = request()->domain().$techn['work_img'];
		//获取技师实时数据
		$techn_last = Db::name('techn_last')->where(['techn_id' => $techn['id']])->find();
		//查询等级名称
		$techn_last['rank_title'] = Db::name('techn_level')->where(['rank' => $techn_last['nature_rank']])->value('title');
		$techn['techn_last'] = $techn_last;
		$start_time = strtotime(date('Y-m-d').' 00:00:00'); //开始时间
		$end_time = strtotime(date('Y-m-d').' 23:59:59'); //结束时间
		//查询技师今日收入
		$techn['today_income'] = Db::name('money_log')->where('identity_type = "techn" and identity_id = '.$techn['id'].' and business_type = 5 and money_type = 0 and operation_type = 1 and add_time >= '.$start_time.' and add_time <= '.$end_time)->sum('operation_money');
		//查询技师今日出行费用
		$techn['today_travel_price'] = Db::name('money_log')->where('identity_type = "techn" and identity_id = '.$techn['id'].' and business_type = 4 and money_type = 0 and operation_type = 1 and add_time >= '.$start_time.' and add_time <= '.$end_time)->sum('operation_money');
		
		
		
		$level_id=db::name('techn_last')->where('techn_id',$techn['id'])->value('level_id');
		
		$info=db::name('techn_level')->where('id',$level_id)->find();
        $next_level = Db::name('techn_level')->where('proxy_id',0)->where('rank',$info['rank']+1)->find();
        $techn_jzl = TechnLevelLogic::jz_v($techn['id'],strtotime(date('y-m-1',time())),time());
		if ($techn_last['total_result']>0 && $next_level['low_result'] > 0){
            $yeji = ($techn_last['total_result'] / $next_level['low_result'])*100;
            if ($yeji > 100){
                $yeji = 100;
            }
        }else{
            $yeji = 100;
        }

        if ($techn_last['total_duration']>0 && $next_level['online_duration'] >0){
            $shichang = ($techn_last['total_duration'] / $next_level['online_duration'])*100;
            if ($shichang > 100){
                $shichang = 100;
            }
        }else{
            $shichang = 100;
        }

        if ($techn_last['total_integral']>0 && $next_level['integral']>0){
            $jifen = ($techn_last['total_integral'] / $next_level['integral'])*100;
            if ($jifen > 100){
                $jifen = 100;
            }
        }else{
            $jifen = 100;
        }

        if ($techn_jzl>0 && $next_level['plus_clock_rate']>0){
            $jiazhonglv = ($techn_jzl / $next_level['plus_clock_rate'])*100;
            if ($jiazhonglv > 100){
                $jiazhonglv = 100;
            }
        }else{
            $jiazhonglv = 100;
        }
        $yeji_bl = (int)(($yeji+$jiazhonglv+$jifen+$shichang)/4);
        $info['yeji_bl'] = $yeji_bl;

        $proxy = Db::name('proxy')->where('is_delete_time',0)->where('qu',$techn['county'])->where('is_xian',1)->find();
        if (empty($proxy)){
            $proxy = Db::name('proxy')->where('is_delete_time',0)->where('shi',$techn['city'])->find();
        }

        if (!empty($proxy)){
            $level_all = Db::name('techn_level')->where('proxy_id',$proxy['proxy_id'])->where('is_delete_time',0)->order('rank asc')->select();
        }else{
            $level_all = Db::name('techn_level')->where('proxy_id',0)->where('is_delete_time',0)->order('rank asc')->select();
        }


        TechnService::TechnPreTimey($techn['id']);
        if ($techn['work_status'] == 1){
            $techn['home_work'] = '接单中';
        }
        if ($techn['work_status'] == 2){
            $techn['home_work'] = '休息中';
        }
        if ($techn['work_status'] == 3){
            $techn['home_work'] = '已下线';
        }
		echo json_encode([
			'code' => 0,
			'msg' => '请求成功',
			'data' => [
				'user' => $user,
				'techn' => $techn,
				'mobile'=>db::name('set')->where('id','1')->value('mobile'),
				'techn_level'=>$info,
				'level_all'=>$level_all,

			]
		]);
	}
	
	
	//上级id修改
	public function upid_change(){
	    
		$techn = $this->techn;
		
		$params = input();
			
		$uptel=$params['upid'];
		
		$uid=db::name('user')->where('mobile',$uptel)->value('id');
		
// 		if(empty($uid)){
// 		    $uid=db::name('techn')->where('mobile',$uptel)->value('user_id');
// 		}
        
        $users_upid=db::name('user')->where('id',$techn['user_id'])->value('upid');
        if(!empty($users_upid)){
		    echo json_encode([
    			'code' => '-1',
    			'msg' => '已绑定上级',
    		]);
    		exit;
		}
        $count=db::name('order')->where(['techn_id'=>$techn['id'],'status'=>['in','1,2,3,4,5,6']])->count();
        
        if($count>0){
            echo json_encode([
    			'code' => '-1',
    			'msg' => '无权限绑定',
    		]);
    		exit;
        }
        
		if(!empty($techn['upid'])){
		    echo json_encode([
    			'code' => '-1',
    			'msg' => '已绑定上级',
    		]);
    		exit;
		}
		if(empty($uid)){
		    echo json_encode([
    			'code' => '-1',
    			'msg' => '该技师未绑定手机端',
    		]);
    		exit;
		}
		if($uid==$techn['user_id']){
		    echo json_encode([
    			'code' => '-1',
    			'msg' => '不可绑定本人',
    		]);
    		exit;
		}
		
		
		db::name('techn')->where('id',$techn['id'])->update(['upid'=>$uid,'bdtime'=>time()]);
		
		team_get($uid);
		team_get2($techn['user_id']);
		
		$result['code'] = 0;
		
		$result['msg'] = "修改成功";
        		
		echo json_encode($result);
	}
	
	
	/**
	 * 我的客户
	 */
	public function kh_lists()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$techn = $this->techn;
		$params = $this->data_post;
		
		$map['khtype']=1;
		$map['balance_type']=3;
		$map['identity_type']='user';
		$map['status']=1;
		$map['identity_id']=$techn['user_id'];
		
		$orderids=db::name('balance')->where($map)->column('order_id');
		
		$user_ids=db::name('order')->where('id','in',$orderids)->column('user_id');
		
		$list_data = Db::name('user')
		             ->where(['id'=>['in',$user_ids]])
		             
		             ->limit(($params['page']-1)*10,10)
		             ->select();
		if(!empty($list_data))
		{
			//遍历处理
			foreach($list_data as $key => $value)
			{
				$list_data[$key]['images'] = $value['avatar'];
			}
			$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data'] = $list_data;
		}else
		{
			$result['code'] = -1;
	        $result['msg'] = "暂无数据";
		}
		
		echo json_encode($result);
	}
    
    
    
    /**
	 * 我的团队
	 */
// 	public function team_lists()
// 	{
// 		$result['code'] = -1;
// 		$result['msg'] = "非法请求";
// 		$techn = $this->techn;
// 		$params = $this->data_post;
		
// 		$map['upid']=$techn['user_id'];
		
// 		$list_data = Db::name('techn')
// 		             ->where($map)
// 		             ->order('bdtime desc')
// 		             ->limit(($params['page']-1)*10,10)
// 		             ->select();
// 		if(!empty($list_data))
// 		{
// 			//遍历处理
// 			foreach($list_data as $key => $value)
// 			{
// 			    $list_data[$key]['bdtime']=date('Y-m-d',$value['bdtime']);
// 				$list_data[$key]['images'] = request()->domain().$value['self_img'];
// 			}
// 			$result['code'] = 0;
// 	        $result['msg'] = "请求成功";
// 	        $result['data'] = $list_data;
// 		}else
// 		{
// 			$result['code'] = -1;
// 	        $result['msg'] = "暂无数据";
// 		}
		
// 		echo json_encode($result);
// 	}
	
	public function team_lists()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$techn = $this->techn;
		
		team_get($techn['id']);
		team_get2($techn['upid']);
		
		$user = db::name('user')->where('id',$techn['user_id'])->find();
		$params = $this->data_post;
		
		$map['user_id']=$user['id'];
		
		$list_data = Db::name('user_bd')
		             ->where($map)
		             ->order('id desc')
		             ->limit(($params['page']-1)*10,10)
		             ->select();
		if(!empty($list_data))
		{
			//遍历处理
			foreach($list_data as $key => $value)
			{
			    $techn=db::name('techn')->where(['user_id'=>$value['bduid'],'upid'=>$user['id']])->find();
			    
			    $users=db::name('user')->where(['id'=>$value['bduid'],'upid'=>$user['id']])->find();
			    
			    $value['bdtime']=!empty($techn)?$techn['bdtime']:$users['bdtime'];
			    $value['self_img']=!empty($techn)?request()->domain().$techn['self_img']:$users['avatar'];
			    $list_data[$key]['nickname']=!empty($techn)?$techn['nickname']:$users['nickname'];
			    $list_data[$key]['mobile']=!empty($techn)?$techn['mobile']:$users['mobile'];
			    $list_data[$key]['bdtime']=date('Y-m-d',$value['bdtime']);
				$list_data[$key]['images'] = $value['self_img'];
			}
			$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data'] = $list_data;
		}else
		{
			$result['code'] = -1;
	        $result['msg'] = "暂无数据";
		}
		
		echo json_encode($result);
	}
	
	
	
	/**
	 * 我的佣金
	 */
	public function yj_lists()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$techn = $this->techn;
		$params = $this->data_post;
		
		
		$map['balance_type']=['in','3,4,5,6'];
		$map['identity_type']='user';
		$map['status']=1;
		$map['identity_id']=$techn['user_id'];
		$map['khtype']=$params['khtype'];
		
		if($params['khtype']==1){//客户
		    $yongjin=db::name('user')->where('id',$techn['user_id'])->value('yongjin');
		}else{
		    $yongjin=db::name('user')->where('id',$techn['user_id'])->value('yongjin2');
		}
		
		
		
		$list_data = Db::name('balance')
		             ->where($map)
		             ->order('id desc')
		             ->limit(($params['page']-1)*10,10)
		             ->select();
		$result_list=[];
		if(!empty($list_data))
		{
			//遍历处理
			foreach($list_data as $key => $value)
			{
			    $result_list[$key]['order_id']=0;
			    if($value['balance_type']==5){
			        $result_list[$key]['title']='申请提现';
			        $result_list[$key]['msg']='';
			        $result_list[$key]['price']='-'.$value['yes_money'];
			    }elseif($value['balance_type']==6){
			        $result_list[$key]['title']='佣金提现驳回';
			        $result_list[$key]['msg']='驳回理由：'.$value['msg'];
			        $result_list[$key]['price']='+'.$value['yes_money'];
			    }else{
			        $result_list[$key]['order_id']=$value['order_id'];
			        $order=db::name('order')->where('id',$value['order_id'])->find();
			        $titles=db::name('order_detail')->where('id',$value['order_id'])->column('title');
			        $titleall=implode(',',$titles);
			        
			        $result_list[$key]['title']=$titleall.'(￥'.$value['price'].')';
			        if($value['balance_type']==3){
			            $result_list[$key]['msg']='昵称：'.db::name('user')->where('id',$value['user_id'])->value('nickname');
			        }else{
			            $result_list[$key]['msg']='昵称：'.db::name('techn')->where('user_id',$value['user_id'])->value('nickname');
			        }
			        
			        $result_list[$key]['msg'].='             下单时间：'.date('Y-m-d H:i:s',$value['add_time']);
			        
			        $result_list[$key]['price']='+'.$value['yes_money'];
			    }
			}
			$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data'] = $result_list;
	        $result['yongjin'] = $yongjin;
		}else
		{
			$result['code'] = -1;
	        $result['msg'] = "暂无数据";
		}
		
		echo json_encode($result);
	}
	
	
	//佣金提现
	public function tixian(){
	    
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$techn = $this->techn;
		$params = $this->data_post;
		
		$user=db::name('user')->where('id',$techn['user_id'])->find();
		
		if($user['yongjin']<=0){
		    $result['code'] = -1;
			$result['msg'] = "佣金提现金额不足";
		    echo json_encode($result);
		    exit;
		}
		
		if($user['yongjin']<=$params['price']){
		    $result['code'] = -1;
			$result['msg'] = "佣金提现金额不足";
		    echo json_encode($result);
		    exit;
		}
		
		//启动事务
			Db::startTrans();
			try{
			    
			    db::name('user')->where('id',$techn['user_id'])->setDec('yongjin',$params['price']);
			    
			    $id=db::name('yj_tixian')->insertGetId([
        		    'user_id'=>$user['id'],
        		    'mobile'=>$params['mobile'],
        		    'real_name'=>$params['real_name'],
        		    'type'=>$params['type'],
        		    'bankname'=>$params['bankname'],
        		    'banknum'=>$params['banknum'],
        		    'price'=>$params['price'],
        		    'zfnum'=>$params['zfnum'],
        		    'add_time'=>time(),
        		    
        		    ]);
        		    
			    db::name('balance')->insert([
        		    'identity_id'=>$user['id'],
        		    'balance_type'=>5,
        		    'order_id'=>$id,
        		    'identity_type'=>'user',
        		    'divide_into'=>0,
        		    'price'=>$params['price'],
        		    'no_money'=>$params['zfnum'],
        		    'yes_money'=>$params['zfnum'],
        		    'msg'=>'佣金提现',
        		    'status'=>1,
        		    'add_time'=>time(),
        		    'upd_time'=>time(),
        		    
        		    ]);
			    
			    
				//提交事务
				Db::commit();
				$result['code'] = 0;
				$result['msg'] = "操作成功";
				
			} catch (\Exception $e) {
				//回滚事务
				Db::rollback();
				$result['code'] = -1;
				$result['msg'] = "操作失败";
			}
		
		echo json_encode($result);
		    exit;
		
		
	}
	
	//补单申诉
	public function order_ss(){
	    
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$techn = $this->techn;
		$params = $this->data_post;

		$info=db::name('order')->where(['techn_id' => $techn['id'],'order_no'=>$params['order_no'],'status'=>14,'order_model'=>0, 'techn_is_repair' => 1, 'techn_repair_sid' => 0])->find();
        if (empty($info)){
            $info=db::name('order')->where(['techn_id' => $techn['id'],'order_no'=>$params['order_no'],'status'=>['<>',6],'order_model'=>0, 'techn_is_repair' => 1, 'techn_repair_sid' => 0])->find();

        }
		
		if(empty($info)){
		    $result['code'] = -1;
			$result['msg'] = "查无此单";
		    echo json_encode($result);
		    exit;
		}
        $jlu = Db::name('order_budan')->where('order_no',$params['order_no'])->where('type',3)->find();
        if (!empty($jlu)){
            $result['code'] = -1;
            $result['msg'] = "已提交申诉";
            echo json_encode($result);
            exit;
        }
		
		$data['add_time']=time();
		$data['order_no']=$params['order_no'];
		$data['techn_id']=$techn['id'];
		$data['reason']=$params['reason'];
		
		db::name('order_budan')->insert($data);
		
		$result['code'] = 0;
		$result['msg'] = "操作成功";
		echo json_encode($result);
		    exit;
				
	}
	
	//补单申诉列表
	public function order_sslist(){
	    
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$techn = $this->techn;
		$params = $this->data_post;
		
		$map=[];
		if(!empty($params['type'])){
		    $map['type']=$params['type'];
		}
		$map['techn_id']=$techn['id'];
		
		
		$list_data = Db::name('order_budan')
		             ->where($map)
		             ->order('id desc')
		             ->limit(($params['page']-1)*10,10)
		             ->select();
		             
		if(!empty($list_data))
		{
			$result['code'] = 0;
	        $result['msg'] = "请求成功";
	        $result['data'] = $list_data;
	        
		}else
		{
			$result['code'] = -1;
	        $result['msg'] = "暂无数据";
		}
		
		echo json_encode($result);
				
	}
	
	
	public function getlevel(){
	    $result['code'] = -1;
		$result['msg'] = "非法请求";
		$techn = $this->techn;
		$params = $this->data_post;

		$level_id=db::name('techn_last')->where('techn_id',$techn['id'])->value('level_id');
        /**
         * 计算加钟率
         */
        $day = Db::name('proxy')->where('shi',$techn['city'])->find();


        $oday=date('d');
        if ($oday <= 15){
            $mins = strtotime(date('Y-m-01',time()));
            $maxs = strtotime(date('Y-m-15',time()));
        }else{
            $mins = strtotime(date('Y-m-16',time()));
            $maxs = strtotime(date('Y-',time()).(date('m',time())+1).'-01');
        }

        
        if (empty($day)){
            $day = 15;
        }

        $jzl = TechnLevelLogic::jz_b($techn['id'],$mins,$maxs);
		$info=db::name('techn_level')->where('id',$level_id)->find();
        $info['level_list'] = TechnLevelLogic::techn_level($techn['id'],$jzl,$day['proxy_id']);


        $info['jzl'] = $jzl;

//        获取小红点
        $have = Db::name('order')->where('techn_id',$techn['id'])->where('status','<',6)->select();
        if (!empty($have)){
            $info['order_list'] = 1;
        }else{
            $info['order_list'] = 0;
        }

//        获取服务结束时间
        $end = Db::name('order')->where('techn_id',$techn['id'])->where('status',5)->find();
        if (!empty($end)){
            $info['end_time'] = $end['service_time'] + ($end['buy_number_duration'] * 60);
        }else{
            $info['end_time'] = 0;
        }
//        $info['next_info'] = $next_info;
        $info['my_last'] = Db::name('techn_last')->where('techn_id',$techn['id'])->find();
		$result['code'] = 0;
        $result['msg'] = "请求成功";
        $result['data'] = $info;
		echo json_encode($result);
	}
	
	
}